package com.project.seckill.service;

import com.project.seckill.bo.KeyPrefix;
import com.project.seckill.util.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * Created by yachao on 2018/6/24.
 */
@Service
public class RedisServiceImpl implements RedisService {

    @Autowired
    private JedisPool jedisPool;

    @Override
    public <T> T get(KeyPrefix keyPrefix, String key, Class<T> cls) {
        Jedis jedis = null;
        try {
            jedis = new Jedis();
            String jsonData = jedis.get(keyWithPrefix(keyPrefix, key));
            return JsonUtils.jsonToBean(jsonData, cls);
        } finally {
            returnToPool(jedis);
        }
    }

    @Override
    public <T> boolean set(KeyPrefix keyPrefix, String key, T value) {
        Jedis jedis = null;
        try {
            jedis = new Jedis();
            String jsonData = JsonUtils.beanToJson(value);
            if (StringUtils.isBlank(jsonData)) {
                return false;
            }
            int seconds = keyPrefix.expireSeconds();
            if (seconds <= 0) {
                jedis.set(keyWithPrefix(keyPrefix, key), jsonData);
            } else {
                jedis.setex(keyWithPrefix(keyPrefix, key), seconds, jsonData);
            }
            return true;
        } finally {
            returnToPool(jedis);
        }
    }

    @Override
    public boolean exists(KeyPrefix keyPrefix, String key) {
        Jedis jedis = null;
        try {
            jedis = jedis();
            return jedis.exists(keyWithPrefix(keyPrefix, key));
        } finally {
            returnToPool(jedis);
        }
    }

    @Override
    public Long incr(KeyPrefix keyPrefix, String key) {
        Jedis jedis = null;
        try {
            jedis = jedis();
            return jedis.incr(keyWithPrefix(keyPrefix, key));
        } finally {
            returnToPool(jedis);
        }
    }

    @Override
    public Long decr(KeyPrefix keyPrefix, String key) {
        Jedis jedis = null;
        try {
            jedis = jedis();
            return jedis.decr(keyWithPrefix(keyPrefix, key));
        } finally {
            returnToPool(jedis);
        }
    }

    private Jedis jedis() {
        return jedisPool.getResource();
    }

    private void returnToPool(Jedis jedis) {
        if (jedis != null) {
            jedis.close();
        }
    }

    private String keyWithPrefix(KeyPrefix keyPrefix, String key) {
        return keyPrefix.getPrefix() + key;
    }
}
